package linkedlist;

import java.util.HashSet;
import java.util.Set;

/**
 * @author justnow
 * Created on 2020-09-30
 * Description
 * 判断是否存在环，返回环的入口节点
 */
public class Leetcode142_HashCycle2 {
    /**
     * 直接用一个hashset来解决这个问题
     * @param head
     * @return
     */
    public ListNode detectCycle(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        ListNode current = head;
        while (current != null) {
            if (set.contains(current)) {
                return current;
            }
            set.add(current);
            current = current.next;
        }
        return null;
    }
}
